import csv
import os
import io
import sys

# 设置UTF-8输出
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

def csv_to_txt(csv_filename, txt_filename):
    try:
        with open(csv_filename, mode='r', encoding='utf-8') as csv_file:
            csv_reader = csv.reader(csv_file)
            with open(txt_filename, mode='w', encoding='utf-8') as txt_file:
                for row in csv_reader:
                    txt_file.write('\t'.join(row) + '\n')
        print(f"✅ 成功将 {csv_filename} 转换为 {txt_filename}")
    except Exception as e:
        print(f"❌ 处理文件时出错: {e}")

def process_csv_files_in_current_dir():
    current_dir = os.path.dirname(os.path.abspath(__file__))
    print("📂 当前目录:", current_dir)

    csv_files = [f for f in os.listdir(current_dir)
                 if f.endswith('.csv') and os.path.isfile(os.path.join(current_dir, f))]

    if not csv_files:
        print("⚠️ 当前目录下没有找到CSV文件")
        return

    for csv_file in csv_files:
        print(f"🔄 正在处理 {csv_file}")
        txt_file = os.path.splitext(csv_file)[0] + '.txt'
        csv_to_txt(os.path.join(current_dir, csv_file), os.path.join(current_dir, txt_file))

if __name__ == "__main__":
    print("🚀 开始处理CSV文件...")
    process_csv_files_in_current_dir()
